// lib/controllers/buy/stock_list_controller.dart
import 'package:drift/drift.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'dart:async';
import 'package:dio/dio.dart';


import '../../../core/network/stock_list_service.dart';
import '../../../core/web/webview_page.dart';
import '../../../data/models/recent_closing_price_model.dart';
import '../../../data/models/sina_stock_model.dart';
import '../../../data/datasource/local/database.dart';


import 'recent_closing_price_controller.dart';


class StockListController extends GetxController {
  final AppDatabase database = Get.find<AppDatabase>();
  final StockListService stockApiService = Get.find<StockListService>();

  final RxList<StockCode> stockCodes = <StockCode>[].obs;
  final RxMap<String, StockModel> stockData = <String, StockModel>{}.obs;
  final RxBool isLoading = false.obs;
  final RxBool isLoadMore = false.obs;
  final RxString searchQuery = ''.obs;
  final ScrollController scrollController = ScrollController();

  int _currentPage = 0;
  final int _pageSize = 50;
  bool _hasMore = true;
  int _lastLoadedIndex = -1;

  // 定时刷新相关变量
  Timer? _refreshTimer;
  final RxBool _isTradingTime = false.obs;
  final RxInt _refreshCount = 0.obs;

  // 添加近期收盘价相关变量
  final RxMap<String, List<RecentClosingPrice>> recentClosingPrices =
      <String, List<RecentClosingPrice>>{}.obs;
  final RxBool isLoadingRecentPrices = false.obs;
  final RecentClosingPriceController recentPriceController = Get.put(
    RecentClosingPriceController(),
  );

  // 添加主要指标数据相关变量
  final RxMap<String, Map<String, dynamic>> mainIndicators =
      <String, Map<String, dynamic>>{}.obs;
  final RxBool isLoadingIndicators = false.obs;
  final Dio _dio = Dio();

  // 添加条件筛选相关变量
  final RxList<StockCode> filteredStocks = <StockCode>[].obs;
  BuyCondition? _filterCondition;

  // 添加可见项跟踪相关变量
  final RxSet<String> _visibleSymbols = <String>{}.obs;

  // 添加用于跟踪当前显示模式的变量
  final RxBool _isFilterMode = false.obs;

  // 添加用于精确计算可见项的变量
  final GlobalKey _listViewKey = GlobalKey();
  final Map<String, GlobalKey> _itemKeys = <String, GlobalKey>{};

  // 添加加载状态跟踪
  final Set<String> _loadingRecentPrices = <String>{};
  final Set<String> _loadingIndicators = <String>{};

  // 添加控制器关闭标志
  bool _isControllerClosed = false;

  // 添加一个新变量来跟踪筛选模式下的总页数
  final RxInt _filteredTotalPages = 0.obs;

  // 添加一个变量来跟踪筛选模式下已处理的股票数量
  final RxInt _processedStocksCount = 0.obs;

  // 添加一个变量来跟踪是否正在处理筛选
  final RxBool _isProcessingFilter = false.obs;

  // 添加一个变量来跟踪所有股票的总数量
  int _totalStocksCount = 0;

  // 添加缓存变量来存储符合上市时间条件的股票
  final RxList<StockCode> _filteredByListingDateStocks = <StockCode>[].obs;

  // 添加变量来跟踪符合每个条件的股票数量
  final RxInt _listingDateFilteredCount = 0.obs;
  final RxInt _recentChangeFilteredCount = 0.obs;
  final RxInt _epsFilteredCount = 0.obs;

  // 添加变量来跟踪当前正在处理的页码
  int _currentProcessingPage = 0;

  // 添加持仓股票代码集合
  var holdStockSymbols = <String>{}.obs;

  @override
  void onInit() {
    super.onInit();
    _isControllerClosed = false;

    // 配置Dio默认选项
    _dio.options = BaseOptions(
      connectTimeout: Duration(seconds: 15),
      receiveTimeout: Duration(seconds: 15),
      validateStatus: (status) {
        return status! < 600;
      },
    );

    loadInitialStockCodes();

    // 监听滚动事件，实现滚动加载
    scrollController.addListener(() {
      // 更新可见项
      _updateVisibleSymbols();

      // 检查是否需要加载更多
      _checkLoadMore();
    });

    // 启动定时器检查交易时间并刷新数据
    _startRefreshTimer();

    loadHoldStockSymbols(); // 添加这行
  }

  @override
  void onClose() {
    _isControllerClosed = true;
    scrollController.removeListener(_checkLoadMore);
    scrollController.dispose();
    _refreshTimer?.cancel();
    _refreshTimer = null;
    // 取消所有正在进行的网络请求
    _dio.close(force: true);
    super.onClose();
  }

  // 检查控制器是否已关闭
  bool get isControllerClosed => _isControllerClosed;

  // 注册列表项的GlobalKey
  void registerItemKey(String symbol, GlobalKey key) {
    if (_isControllerClosed) return;
    _itemKeys[symbol] = key;
  }

  // 取消注册列表项的GlobalKey
  void unregisterItemKey(String symbol) {
    if (_isControllerClosed) return;
    _itemKeys.remove(symbol);
  }

  // 检查是否需要加载更多数据
  void _checkLoadMore() {
    if (_isControllerClosed) return;

    if (scrollController.position.pixels >=
        scrollController.position.maxScrollExtent - 200) {
      if (!isLoadMore.value && _hasMore) {
        loadMoreStockCodes();
      }
    }
  }

  // 更新可见项 - 使用GlobalKey精确计算
  void _updateVisibleSymbols() {
    if (_isControllerClosed) return;

    final visibleSymbols = _calculateVisibleSymbols();

    // 只有当可见项发生变化时才更新
    if (_visibleSymbols.length != visibleSymbols.length ||
        !_visibleSymbols.containsAll(visibleSymbols)) {
      _visibleSymbols.value = visibleSymbols;
    }
  }

  // 使用GlobalKey精确计算可见项
  Set<String> _calculateVisibleSymbols() {
    final visibleSymbols = <String>{};
    if (_isControllerClosed) return visibleSymbols;

    // 确定当前显示的股票列表
    final currentStocks = _isFilterMode.value ? filteredStocks : stockCodes;

    if (currentStocks.isEmpty) return visibleSymbols;

    // 获取ListView的渲染对象
    final RenderBox? listViewRenderBox =
    _listViewKey.currentContext?.findRenderObject() as RenderBox?;
    if (listViewRenderBox == null) return visibleSymbols;

    // 获取ListView在屏幕中的位置和大小
    final listViewOffset = listViewRenderBox.localToGlobal(Offset.zero);
    final listViewHeight = listViewRenderBox.size.height;

    // 遍历所有已注册的列表项
    for (final symbol in _itemKeys.keys) {
      final GlobalKey itemKey = _itemKeys[symbol]!;
      final RenderBox? itemRenderBox =
      itemKey.currentContext?.findRenderObject() as RenderBox?;

      if (itemRenderBox != null) {
        // 获取列表项在屏幕中的位置和大小
        final itemOffset = itemRenderBox.localToGlobal(Offset.zero);
        final itemHeight = itemRenderBox.size.height;

        // 检查列表项是否在ListView的可见区域内
        if (itemOffset.dy + itemHeight >= listViewOffset.dy &&
            itemOffset.dy <= listViewOffset.dy + listViewHeight) {
          visibleSymbols.add(symbol);
        }
      }
    }

    return visibleSymbols;
  }

  // 添加公共方法用于外部调用
  void updateVisibleSymbols() {
    if (_isControllerClosed) return;
    _updateVisibleSymbols();
  }

  // 获取持仓股票代码
  Future<void> loadHoldStockSymbols() async {
    try {
      final buyRecords = await database.allBuyRecords;
      final symbols = buyRecords
          .where((record) => record.remainingQuantity > 0)
          .map((record) => record.symbol)
          .toSet();
      holdStockSymbols.assignAll(symbols);
      print('持仓股票数: ${symbols.length}');
    } catch (e) {
      print('加载持仓股票代码失败: $e');
    }
  }


  // 设置筛选条件
  void setFilterCondition(BuyCondition condition) {
    if (_isControllerClosed) return;

    _filterCondition = condition;
    _isFilterMode.value = true;
    // 清空缓存
    _filteredByListingDateStocks.clear();
    // 重置计数器
    _listingDateFilteredCount.value = 0;
    _recentChangeFilteredCount.value = 0;
    _epsFilteredCount.value = 0;
    _currentPage = 0;
    _currentProcessingPage = 0;
    _processedStocksCount.value = 0;
    // 立即加载第一页筛选数据
    loadFirstPageWithFilter();
  }

  // 添加加载第一页筛选数据的方法
  void loadFirstPageWithFilter() {
    if (_isControllerClosed) return;

    _currentPage = 0;
    _currentProcessingPage = 0;
    _hasMore = true;
    _lastLoadedIndex = -1;
    filteredStocks.clear();

    // 立即加载第一页
    loadNextPageWithFilter();
  }

  // 带筛选条件的数据刷新
  Future<void> refreshDataWithFilter() async {
    if (_isControllerClosed) return;

    _currentPage = 0;
    _currentProcessingPage = 0;
    _hasMore = true;
    _lastLoadedIndex = -1;
    stockData.clear();
    recentClosingPrices.clear();
    mainIndicators.clear();
    filteredStocks.clear();
    _filteredByListingDateStocks.clear(); // 清空缓存
    // 重置计数器
    _listingDateFilteredCount.value = 0;
    _recentChangeFilteredCount.value = 0;
    _epsFilteredCount.value = 0;
    _processedStocksCount.value = 0;

    // 只加载股票代码，不自动加载数据
    isLoading.value = true;
    try {
      final allCodes = await database.allStockCodes;
      stockCodes.assignAll(allCodes);
      _totalStocksCount = allCodes.length;
      print("总股票数量: $_totalStocksCount");

      // 加载第一页筛选数据
      loadNextPageWithFilter();
    } catch (e) {
      Get.snackbar('错误', '加载股票代码失败: $e');
    } finally {
      if (!_isControllerClosed) {
        isLoading.value = false;
      }
    }
  }

  // 修改 loadNextPageWithFilter 方法
  Future<void> loadNextPageWithFilter() async {
    if (_isControllerClosed || isLoadMore.value || !_hasMore || _isProcessingFilter.value) return;

    _isProcessingFilter.value = true;
    isLoadMore.value = true;

    try {
      // 使用当前处理页码加载数据
      await loadStockDataForPageWithFilter(_currentProcessingPage);

      // 更新已处理的股票数量
      _processedStocksCount.value = ((_currentProcessingPage + 1) * _pageSize);
      if (_processedStocksCount.value > _filteredByListingDateStocks.length) {
        _processedStocksCount.value = _filteredByListingDateStocks.length;
      }

      // 更新总页数
      _filteredTotalPages.value = (_filteredByListingDateStocks.length / _pageSize).ceil();

      // 检查是否还有更多数据
      _hasMore = _processedStocksCount.value < _filteredByListingDateStocks.length;

      // 增加当前处理页码
      _currentProcessingPage++;

      // 更新当前页码显示
      _currentPage = _currentProcessingPage;

      // 刷新UI
      filteredStocks.refresh();

      print("已处理 $_processedStocksCount / ${_filteredByListingDateStocks.length} 只股票，当前页: $_currentPage, 总页数: ${_filteredTotalPages.value}, 还有更多数据: $_hasMore");
    } catch (e) {
      if (!_isControllerClosed) {
        Get.snackbar('错误', '加载下一页筛选数据失败: $e');
      }
    } finally {
      if (!_isControllerClosed) {
        isLoadMore.value = false;
        _isProcessingFilter.value = false;
      }
    }
  }

  // 修改 loadStockDataForPageWithFilter 方法中的EPS筛选逻辑
  Future<void> loadStockDataForPageWithFilter(int page) async {
    if (_isControllerClosed) return;

    // 第一步：如果缓存为空，先从数据库查询所有符合上市时间条件的股票
    if (_filteredByListingDateStocks.isEmpty) {
      if (_filterCondition?.listingDate != null) {
        // 查询数据库获取所有符合上市时间条件的股票
        final query = database.select(database.stockCodes)
          ..where((t) => t.listingDate.isNotNull() & t.listingDate.isBiggerOrEqualValue(_filterCondition!.listingDate!));

        final results = await query.get();
        _filteredByListingDateStocks.assignAll(results);
        _listingDateFilteredCount.value = results.length;
        print("从数据库查询到符合上市时间条件的股票数量: ${_listingDateFilteredCount.value}");
      } else {
        // 如果没有上市时间条件，使用所有股票
        _filteredByListingDateStocks.assignAll(stockCodes);
        _listingDateFilteredCount.value = stockCodes.length;
        print("使用所有股票作为基础数据集，数量: ${_listingDateFilteredCount.value}");
      }

      // 如果没有符合条件的股票，直接返回
      if (_filteredByListingDateStocks.isEmpty) {
        _hasMore = false;
        _filteredTotalPages.value = 0;
        _processedStocksCount.value = 0;
        return;
      }
    }

    final startIndex = page * _pageSize;
    if (startIndex >= _filteredByListingDateStocks.length) {
      _hasMore = false;
      return;
    }

    final endIndex = (page + 1) * _pageSize;
    final currentBatch = _filteredByListingDateStocks.sublist(
      startIndex,
      endIndex > _filteredByListingDateStocks.length ? _filteredByListingDateStocks.length : endIndex,
    );

    print("当前批次股票数量: ${currentBatch.length}, 页码: $page, 开始索引: $startIndex, 结束索引: $endIndex");

    // 第二步：获取当前批次股票的实时数据
    await fetchStockDataForBatch(currentBatch);

    // 第三步：从当前批次的股票中筛选符合近期涨跌幅条件的股票
    final List<StockCode> filteredByRecentChange = [];
    if (_filterCondition?.recentChange != null) {
      // 加载近期收盘价数据
      await loadRecentPricesForBatch(currentBatch);

      for (final code in currentBatch) {
        final recentPrices = getRecentPrices(code.symbol);
        final stockModel = stockData[code.symbol];

        if (recentPrices.isNotEmpty &&
            recentPrices.length >= 4 &&
            stockModel != null) {
          final currentPrice = stockModel.currentPrice;
          final fourthDayPrice = recentPrices[3].close;

          if (currentPrice > 0 && fourthDayPrice > 0) {
            final priceChangePercent =
                ((currentPrice - fourthDayPrice) / fourthDayPrice) * 100;

            print(
              "${code.symbol}: 当前价=$currentPrice, 四天前价=$fourthDayPrice, 涨跌幅=$priceChangePercent%",
            );

            if (priceChangePercent < _filterCondition!.recentChange!) {
              filteredByRecentChange.add(code);
            }
          }
        }
      }
      _recentChangeFilteredCount.value += filteredByRecentChange.length;
    } else {
      // 如果没有近期涨跌幅条件，使用当前批次的所有股票
      filteredByRecentChange.addAll(currentBatch);
      _recentChangeFilteredCount.value += currentBatch.length;
    }

    print("符合近期涨跌幅条件的股票数量: ${filteredByRecentChange.length}");

    // 第四步：从符合前两个条件的股票中筛选符合每股收益条件的股票
    final List<StockCode> filteredByEps = [];
    if (_filterCondition?.eps != null) {
      // 加载财务指标数据
      await loadIndicatorsForBatch(filteredByRecentChange);

      for (final code in filteredByRecentChange) {
        final indicators = getMainIndicators(code.symbol);

        // 检查是否有年度数据
        if (indicators.containsKey('year') && indicators['year'] is List) {
          final yearData = indicators['year'] as List;

          // 获取最新一年的数据（假设最新数据在第一项）
          if (yearData.isNotEmpty) {
            final latestYearData = yearData[0];

            // 检查数据格式并提取EPS值
            double? eps;

            // 尝试不同的EPS字段名称
            if (latestYearData is Map<String, dynamic>) {
              // 尝试常见的EPS字段名称
              if (latestYearData.containsKey('F004N')) {
                eps = _parseDouble(latestYearData['F004N']);
              } else if (latestYearData.containsKey('eps')) {
                eps = _parseDouble(latestYearData['eps']);
              } else if (latestYearData.containsKey('EPS')) {
                eps = _parseDouble(latestYearData['EPS']);
              } else if (latestYearData.containsKey('basic_eps')) {
                eps = _parseDouble(latestYearData['basic_eps']);
              }

              // 打印调试信息
              print("${code.symbol} 的EPS值: $eps, 要求EPS: ${_filterCondition!.eps!}");

              // 如果找到了EPS值并且符合条件
              if (eps != null && eps > _filterCondition!.eps!) {
                filteredByEps.add(code);
              } else if (eps == null) {
                print("${code.symbol} 没有找到EPS字段");
              }
            }
          } else {
            print("${code.symbol} 年度数据为空");
          }
        } else {
          print("${code.symbol} 没有年度数据");
        }
      }
      _epsFilteredCount.value += filteredByEps.length;
    } else {
      // 如果没有EPS条件，使用所有符合前两个条件的股票
      filteredByEps.addAll(filteredByRecentChange);
      _epsFilteredCount.value += filteredByRecentChange.length;
    }

    print("符合EPS条件的股票数量: ${filteredByEps.length}");

    // 最后，将符合条件的股票添加到筛选结果列表中
    for (final code in filteredByEps) {
      if (!filteredStocks.any((s) => s.symbol == code.symbol)) {
        filteredStocks.add(code);
      }
    }

    // 刷新UI
    filteredStocks.refresh();

    // 打印调试信息
    print("当前已找到 ${filteredStocks.length} 只符合条件的股票");
    print("还有更多数据: $_hasMore, 已处理股票数量: ${_processedStocksCount.value}");
  }

  // 辅助方法：解析double值
  double? _parseDouble(dynamic value) {
    if (value == null) return null;

    if (value is double) return value;
    if (value is int) return value.toDouble();
    if (value is String) {
      try {
        return double.parse(value);
      } catch (e) {
        print("无法将字符串 '$value' 转换为double: $e");
        return null;
      }
    }

    return null;
  }

  // 清除筛选条件
  void clearFilter() {
    if (_isControllerClosed) return;

    _filterCondition = null;
    _isFilterMode.value = false;
    filteredStocks.clear();
    _filteredByListingDateStocks.clear(); // 清空缓存
    // 重置计数器
    _listingDateFilteredCount.value = 0;
    _recentChangeFilteredCount.value = 0;
    _epsFilteredCount.value = 0;
    _hasMore = true;
    _currentPage = 0;
    _currentProcessingPage = 0;
    _processedStocksCount.value = 0;
  }

  // 检查是否有筛选条件
  bool get hasFilter => _filterCondition != null;

  // 检查是否还有更多数据
  bool get hasMore => _hasMore;

  // 获取当前筛选条件
  BuyCondition? get selectedCondition => _filterCondition;

  // 获取主要指标数据的方法
  Future<void> fetchMainIndicators(String symbol, {bool force = false}) async {
    if (_isControllerClosed) return;

    if (!force &&
        mainIndicators.containsKey(symbol) &&
        mainIndicators[symbol]!.isNotEmpty) {
      return; // 如果已经有数据且不是强制刷新，不再重复获取
    }

    // 检查是否已经在加载中
    if (_loadingIndicators.contains(symbol)) {
      return;
    }

    _loadingIndicators.add(symbol);
    isLoadingIndicators.value = true;

    try {
      // 提取纯数字代码
      String pureCode = symbol;
      if (symbol.contains('.')) {
        pureCode = symbol.substring(symbol.indexOf('.') + 1);
      }

      final response = await _dio.get(
        'http://www.cninfo.com.cn/data20/financialData/getMainIndicators?scode=$pureCode&sign=2',
        options: Options(
          headers: {
            "Accept": "application/json, text/plain, */*",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "no-cache",
            "Cookie":
            "cninfo_user_browse=600000,gssh0600000,%E6%B5%A6%E5%8F%91%E9%93%B6%E8%A1%8C|000009,gssz0000009,%E4%B8%AD%E5%9B%BD%E5%AE%9D%E5%AE%89|600004,gssh0600004,%E7%99%BD%E4%BA%91%E6%9C%BA%E5%9C%BA; insert_cookie=45380249; _sp_ses.2141=*; SF_cookie_4=40016378; routeId=.uc2; _sp_id.2141=18df8047-e0a5-4f61-b11d-f091b056f81f.1707967494.10.1710073501.1710055348.3dd96828-caf8-4a5a-b1bb-e4a54242b91d; SID=58338444-5268-4ce4-8857-5c2d87ffb130",
            "Pragma": "no-cache",
            "Proxy-Connection": "keep-alive",
            "Referer":
            "http://www.cninfo.com.cn/new/disclosure/stock?stockCode=$pureCode&orgId=gssh0$pureCode",
            "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.289 Safari/537.36",
          },
        ),
      );

      if (response.statusCode == 200) {
        final data = response.data;

        if (data != null &&
            data['data'] != null &&
            data['data']['records'] != null) {
          final records = data['data']['records'] as List;
          if (records.isNotEmpty) {
            final record = records[0];

            // 提取所有类型的数据
            Map<String, dynamic> indicators = {};

            // 年度数据
            if (record['year'] != null && (record['year'] as List).isNotEmpty) {
              indicators['year'] = record['year'];
            }

            // 第三季度数据
            if (record['three'] != null &&
                (record['three'] as List).isNotEmpty) {
              indicators['three'] = record['three'];
            }

            // 年中数据
            if (record['middle'] != null &&
                (record['middle'] as List).isNotEmpty) {
              indicators['middle'] = record['middle'];
            }

            // 第一季度数据
            if (record['one'] != null && (record['one'] as List).isNotEmpty) {
              indicators['one'] = record['one'];
            }

            // 更新数据并通知监听者
            if (!_isControllerClosed) {
              mainIndicators[symbol] = indicators;
              mainIndicators.refresh(); // 手动触发更新
            }
          }
        }
      }
    } catch (e) {
      print('获取主要指标数据失败: $e');
      // 即使失败也设置一个空Map，避免重复尝试
      if (!_isControllerClosed) {
        mainIndicators[symbol] = {};
        mainIndicators.refresh(); // 手动触发更新
      }
    } finally {
      if (!_isControllerClosed) {
        _loadingIndicators.remove(symbol);
        isLoadingIndicators.value = _loadingIndicators.isNotEmpty;
      }
    }
  }

  // 添加加载指定批次股票主要指标数据的方法
  Future<void> loadIndicatorsForBatch(List<StockCode> batch) async {
    if (_isControllerClosed) return;

    for (final stockCode in batch) {
      if (!mainIndicators.containsKey(stockCode.symbol) ||
          mainIndicators[stockCode.symbol]!.isEmpty) {
        await fetchMainIndicators(stockCode.symbol);
      }
    }
  }

  // 获取主要指标数据的方法
  Map<String, dynamic> getMainIndicators(String symbol) {
    return mainIndicators[symbol] ?? {};
  }

  // 获取近期收盘价的方法
  Future<void> fetchRecentClosingPrices(String symbol) async {
    if (_isControllerClosed) return;

    // 如果已经有数据或正在加载，不再重复获取
    if (recentClosingPrices.containsKey(symbol) &&
        recentClosingPrices[symbol]!.isNotEmpty) {
      return;
    }

    // 检查是否已经在加载中
    if (_loadingRecentPrices.contains(symbol)) {
      return;
    }

    _loadingRecentPrices.add(symbol);
    isLoadingRecentPrices.value = true;

    try {
      // 创建一个新的控制器实例，避免多个股票共用同一个控制器
      final RecentClosingPriceController priceController =
      RecentClosingPriceController();
      priceController.updateStockCode(symbol);
      await priceController.fetchStockData();

      // 存储获取到的数据
      if (!_isControllerClosed) {
        recentClosingPrices[symbol] = List.from(
          priceController.recentClosingPriceList,
        );
        recentClosingPrices.refresh(); // 通知UI更新
      }
    } catch (e) {
      print('获取近期收盘价失败: $e');
      // 即使失败也设置一个空列表，避免重复尝试
      if (!_isControllerClosed) {
        recentClosingPrices[symbol] = [];
        recentClosingPrices.refresh(); // 通知UI更新
      }
    } finally {
      if (!_isControllerClosed) {
        _loadingRecentPrices.remove(symbol);
        isLoadingRecentPrices.value = _loadingRecentPrices.isNotEmpty;
      }
    }
  }

  // 添加加载指定批次股票近期收盘价的方法
  Future<void> loadRecentPricesForBatch(List<StockCode> batch) async {
    if (_isControllerClosed) return;

    for (final stockCode in batch) {
      if (!recentClosingPrices.containsKey(stockCode.symbol) ||
          recentClosingPrices[stockCode.symbol]!.isEmpty) {
        await fetchRecentClosingPrices(stockCode.symbol);
      }
    }
  }

  // 获取指定股票近期收盘价的方法
  List<RecentClosingPrice> getRecentPrices(String symbol) {
    return recentClosingPrices[symbol] ?? [];
  }

  Future<void> loadInitialStockCodes() async {
    if (_isControllerClosed) return;

    isLoading.value = true;
    try {
      final allCodes = await database.allStockCodes;
      stockCodes.assignAll(allCodes);
      _totalStocksCount = allCodes.length;

      // 加载第一页数据
      await loadStockDataForPage(0);
      _lastLoadedIndex = _pageSize - 1;
    } catch (e) {
      if (!_isControllerClosed) {
        Get.snackbar('错误', '加载股票代码失败: $e');
      }
    } finally {
      if (!_isControllerClosed) {
        isLoading.value = false;
      }
    }
  }

  // 启动定时刷新
  void _startRefreshTimer() {
    if (_isControllerClosed) return;

    // 先立即检查一次交易时间
    _checkTradingTime();

    // 设置定时器，每隔1分钟检查一次交易时间
    _refreshTimer = Timer.periodic(Duration(minutes: 1), (timer) {
      if (_isControllerClosed) {
        timer.cancel();
        return;
      }
      _checkTradingTime();
    });
  }

  // 检查是否在交易时间内
  void _checkTradingTime() {
    if (_isControllerClosed) return;

    final now = DateTime.now();
    final weekday = now.weekday;

    // 检查是否是工作日（周一到周五）
    if (weekday >= DateTime.monday && weekday <= DateTime.friday) {
      final time = now.hour * 100 + now.minute;

      // 检查是否在交易时间内（上午9:30-11:30，下午13:00-15:00）
      final isTradingTime =
          (time >= 930 && time <= 1130) || (time >= 1300 && time <= 1500);

      if (isTradingTime != _isTradingTime.value) {
        _isTradingTime.value = isTradingTime;

        if (isTradingTime) {
          // 开始交易时间，启动3秒刷新定时器
          _startTradingRefreshTimer();
        } else {
          // 结束交易时间，停止刷新定时器
          _stopTradingRefreshTimer();
        }
      }
    } else if (_isTradingTime.value) {
      // 非工作日但之前是交易时间，停止刷新
      _isTradingTime.value = false;
      _stopTradingRefreshTimer();
    }
  }

  // 启动交易时间内的3秒刷新定时器
  void _startTradingRefreshTimer() {
    if (_isControllerClosed) return;

    // 先停止可能存在的旧定时器
    _stopTradingRefreshTimer();

    // 创建新的定时器，每3秒刷新一次
    _refreshTimer = Timer.periodic(Duration(seconds: 3), (timer) {
      if (_isControllerClosed) {
        timer.cancel();
        return;
      }
      _refreshVisibleStocks();
    });
  }

  // 停止交易时间刷新定时器
  void _stopTradingRefreshTimer() {
    _refreshTimer?.cancel();
    _refreshTimer = null;
  }

  // 刷新当前可见的股票数据
  Future<void> _refreshVisibleStocks() async {
    if (_isControllerClosed || isLoading.value || isLoadMore.value) return;

    // 获取当前可见的股票代码
    final visibleSymbols = _calculateVisibleSymbols();
    if (visibleSymbols.isEmpty) return;

    try {
      final symbols = visibleSymbols.toList();
      final dataMap = await stockApiService.fetchStockData(symbols);

      for (final symbol in dataMap.keys) {
        try {
          final stockModel = StockModel.fromSinaData(symbol, dataMap[symbol]!);
          if (!_isControllerClosed) {
            stockData[symbol] = stockModel;
          }
        } catch (e) {
          print('解析股票数据失败: $symbol, $e');
        }
      }
      if (!_isControllerClosed) {
        stockData.refresh(); // 通知UI更新
        _refreshCount.value++; // 增加刷新计数
      }
      print('刷新了 ${symbols.length} 只可见股票: ${symbols.join(', ')}');
    } catch (e) {
      print('刷新股票数据失败: $e');
    }
  }

  Future<void> loadMoreStockCodes() async {
    if (_isControllerClosed || isLoadMore.value || !_hasMore) return;

    isLoadMore.value = true;

    try {
      if (_filterCondition != null) {
        await loadNextPageWithFilter();
      } else {
        _currentPage++;
        await loadStockDataForPage(_currentPage);
        _lastLoadedIndex = ((_currentPage + 1) * _pageSize) - 1; // 更新最后加载的索引
        if (_lastLoadedIndex >= stockCodes.length) {
          _lastLoadedIndex = stockCodes.length - 1;
          _hasMore = false;
        }
      }
    } catch (e) {
      if (!_isControllerClosed) {
        Get.snackbar('错误', '加载更多股票失败: $e');
      }
      _currentPage--; // 回退页码
      _hasMore = false; // 标记没有更多数据
    } finally {
      if (!_isControllerClosed) {
        isLoadMore.value = false;
      }
    }
  }

  Future<void> loadStockDataForPage(int page) async {
    if (_isControllerClosed) return;

    final startIndex = page * _pageSize;
    if (startIndex >= stockCodes.length) {
      _hasMore = false;
      return;
    }

    final endIndex = (page + 1) * _pageSize;
    final currentBatch = stockCodes.sublist(
      startIndex,
      endIndex > stockCodes.length ? stockCodes.length : endIndex,
    );

    // 检查是否还有更多数据
    _hasMore = endIndex < stockCodes.length;

    // 先加载所有必要的数据
    await loadRecentPricesForBatch(currentBatch);
    await loadIndicatorsForBatch(currentBatch);

    // 然后获取股票数据
    await fetchStockDataForBatch(currentBatch);
  }

  // 修改 fetchStockDataForBatch 方法
  Future<void> fetchStockDataForBatch(List<StockCode> batch) async {
    if (_isControllerClosed || batch.isEmpty) return;

    try {
      final symbols = batch.map((code) => code.symbol).toList();
      final dataMap = await stockApiService.fetchStockData(symbols);

      for (final symbol in dataMap.keys) {
        try {
          // 只有当数据不存在或者需要更新时才设置新数据
          if (!stockData.containsKey(symbol) ||
              stockData[symbol]?.currentPrice == 0) {
            final stockModel = StockModel.fromSinaData(
              symbol,
              dataMap[symbol]!,
            );
            if (!_isControllerClosed) {
              stockData[symbol] = stockModel;
            }
          }
        } catch (e) {
          print('解析股票数据失败: $symbol, $e');
          // 只有在没有数据时才创建默认数据
          if (!stockData.containsKey(symbol)) {
            if (!_isControllerClosed) {
              stockData[symbol] = StockModel(
                name: symbol,
                symbol: symbol,
                currentPrice: 0,
                yesterdayClose: 0,
                todayOpen: 0,
                high: 0,
                low: 0,
                volume: 0,
                amount: 0,
                date: DateTime.now(),
                time: DateTime.now(),
              );
            }
          }
        }
      }
      if (!_isControllerClosed) {
        stockData.refresh(); // 通知UI更新
      }
    } catch (e) {
      print('获取股票数据失败: $e');
      // 为当前批次的股票创建默认数据（只有在没有数据时）
      for (final code in batch) {
        if (!stockData.containsKey(code.symbol)) {
          if (!_isControllerClosed) {
            stockData[code.symbol] = StockModel(
              name: code.name ?? code.symbol,
              symbol: code.symbol,
              currentPrice: 0,
              yesterdayClose: 0,
              todayOpen: 0,
              high: 0,
              low: 0,
              volume: 0,
              amount: 0,
              date: DateTime.now(),
              time: DateTime.now(),
            );
          }
        }
      }
      if (!_isControllerClosed) {
        stockData.refresh(); // 通知UI更新
      }
    }
  }

  Future<void> refreshData() async {
    if (_isControllerClosed) return;

    if (_filterCondition != null) {
      await refreshDataWithFilter();
    } else {
      _currentPage = 0;
      _hasMore = true;
      _lastLoadedIndex = -1;
      stockData.clear();
      recentClosingPrices.clear();
      mainIndicators.clear(); // 清空主要指标数据
      await loadInitialStockCodes();
    }
  }

  Future<void> searchStock(String query) async {
    if (_isControllerClosed) return;

    searchQuery.value = query;

    if (query.isEmpty) {
      await refreshData();
      return;
    }

    // 检查是否为6位数字
    final isSixDigitCode = RegExp(r'^\d{6}$').hasMatch(query);

    if (!isSixDigitCode) {
      // 如果不是6位数字，清空结果
      stockCodes.clear();
      stockData.clear();
      recentClosingPrices.clear();
      mainIndicators.clear();
      isLoading.value = false;
      return;
    }

    isLoading.value = true;
    try {
      final allCodes = await database.allStockCodes;

      // 只搜索6位完整股票代码
      final filteredCodes = allCodes.where((code) {
        // 提取股票代码的数字部分（去掉市场前缀）
        final codeDigits = code.symbol.split('.').last;
        return codeDigits == query;
      }).toList();

      stockCodes.assignAll(filteredCodes);
      _totalStocksCount = filteredCodes.length;
      stockData.clear();
      recentClosingPrices.clear();
      mainIndicators.clear();

      // 重新加载数据
      _currentPage = 0;
      _hasMore = filteredCodes.isNotEmpty;
      _lastLoadedIndex = -1;

      if (filteredCodes.isNotEmpty) {
        // 加载第一页数据
        await loadStockDataForPage(0);
        _lastLoadedIndex = _pageSize - 1;
        if (_lastLoadedIndex >= filteredCodes.length) {
          _lastLoadedIndex = filteredCodes.length - 1;
          _hasMore = false;
        }
      }
    } catch (e) {
      if (!_isControllerClosed) {
        Get.snackbar('错误', '搜索股票失败: $e');
      }
    } finally {
      if (!_isControllerClosed) {
        isLoading.value = false;
      }
    }
  }

  // 在 StockListController 类中添加以下方法
  // 检查是否还有更多数据需要加载
  bool get hasMoreData {
    if (_isControllerClosed) return false;

    if (_filterCondition != null) {
      // 在筛选模式下，检查是否还有更多股票代码需要处理
      return _hasMore && _processedStocksCount.value < _filteredByListingDateStocks.length;
    } else {
      // 在普通模式下，检查是否还有更多股票代码
      return _hasMore;
    }
  }

  // 获取当前页码
  int get currentPage => _currentPage;

  // 修改 totalPages 计算方法
  int get totalPages {
    if (_isControllerClosed) return 0;

    if (_filterCondition != null) {
      // 在筛选模式下，使用专门计算的总页数
      return _filteredTotalPages.value;
    } else {
      // 在普通模式下，总页数基于当前显示的股票数量
      if (stockCodes.isEmpty) return 0;
      return (stockCodes.length / _pageSize).ceil();
    }
  }

  // 添加一个方法来获取当前已加载的筛选结果数量
  int get loadedFilteredCount => filteredStocks.length;

  // 添加一个方法来获取当前批次处理的股票数量
  int get currentBatchSize {
    final startIndex = _currentPage * _pageSize;
    if (startIndex >= _filteredByListingDateStocks.length) return 0;

    final endIndex = (_currentPage + 1) * _pageSize;
    return endIndex > _filteredByListingDateStocks.length
        ? _filteredByListingDateStocks.length - startIndex
        : _pageSize;
  }

  // 添加一个方法来获取当前已处理的股票数量
  int get processedStocksCount => _processedStocksCount.value;

  // 添加一个方法来获取是否正在处理筛选
  bool get isProcessingFilter => _isProcessingFilter.value;

  // 添加一个方法来获取所有股票的总数量
  int get totalStocksCount => _totalStocksCount;

  // 添加获取符合各条件股票数量的方法
  int get listingDateFilteredCount => _listingDateFilteredCount.value;
  int get recentChangeFilteredCount => _recentChangeFilteredCount.value;
  int get epsFilteredCount => _epsFilteredCount.value;

  String getSecurityTypeName(int type) {
    switch (type) {
      case 1:
        return '股票';
      case 2:
        return '基金';
      case 3:
        return '债券';
      default:
        return '其他';
    }
  }

  String getListingStatusName(int status) {
    switch (status) {
      case 1:
        return '上市';
      case 2:
        return '退市';
      default:
        return '未知';
    }
  }

  void clickLookStock(String code) {
    String prefix = code.substring(0, 2); // hs / sh / sz
    String number = code.substring(2); // 000506
    String stockCode = '${prefix}_$number';
    String loadResource = "https://m.10jqka.com.cn/stockpage/$stockCode"; //同花顺
    loadResource =
    "https://pqa9p2.smartapps.baidu.com/pages/quote/quote?market=ab&type=stock&code=$number"; //百度
    if (prefix == "sh" || prefix == "sz") {
      if (number.startsWith("5") || number.startsWith("1")) {
        //基金
        loadResource = "https://m.10jqka.com.cn/stockpage/hs_$number";
      }
    }
    // loadResource = "https://xueqiu.com/S/sh601126/";
    Get.to(() => WebViewPage(
      loadResource: loadResource,
    ));
  }


  // 获取刷新计数（用于UI显示）
  int get refreshCount => _refreshCount.value;

  // 获取是否在交易时间（用于UI显示）
  bool get isTradingTime => _isTradingTime.value;

  // 获取ListView的Key
  GlobalKey get listViewKey => _listViewKey;
}